<template>
  <div>
    <el-dialog :title="'已绑定' + title"
               :visible.sync="bindDialog.visible"
               width="90%">
      <manage-page
        :autoQuery="true"
        :basePath="bindBasePath"
        :conditionLayout="2"
        :customTable="customTable"
        :defaultConditionParam="bindDialog.defaultCondition"
        :doubleClickModify="false"
        :leftButton1="addButton"
        :leftButton2="unbindButton"
        :multiSelect="true"
        :rightButton1="positionButton"
        @handleSelectionChange="handleBindTableSelectionChange"
        @handleCurrentChange="handleBindTableCurrentChange"
        @handleQueryData="handleBindTableQueryData"
        @leftButton1Handler="handleAddButton"
        @leftButton2Handler="handleUnbindButton"
        @rightButton1Handler="handlePositionButton"
        ref="bindTable"
      >
        <span slot="custom-table">替换table</span>
      </manage-page>
    </el-dialog>
    <el-dialog :title="'待绑定' + title"
               :visible.sync="unbindDialog.visible"
               width="80%">
      <manage-page
        :autoQuery="true"
        :basePath="bindBasePath"
        :conditionLayout="2"
        :customTable="customTable"
        :doubleClickModify="false"
        :leftButton1="bindButton"
        :multiSelect="true"
        @handleSelectionChange="handleUnbindTableSelectionChange"
        @handleCurrentChange="handleUnbindTableCurrentChange"
        @handleQueryData="handleUnbindTableQueryData"
        @leftButton1Handler="handleBindButton"
        @queryUnbind="queryUnbind"
        customerQueryFunction="queryUnbind"
        ref="unbindTable"
      >
        <span slot="custom-table">替换table</span>
      </manage-page>
    </el-dialog>
  </div>
</template>

<script>
import managePage from '@/components/ManagePage'

export default {
  name: 'relationPage',
  props: {
    /** ===========全局配置============= **/
    conditionLayout: {
      type: Number,
      default: () => {
        return 2
      }
    },
    basePath: {
      type: String,
      default: () => {
        return null
      }
    },
    title: {
      type: String,
      default: () => {
        return ''
      }
    },
    masterCurrentRow: {
      type: Object,
      default: () => {
        return null
      }
    },
    customTable: Boolean
  },
  components: {
    managePage
  },
  watch: {
    basePath: {
      handler (newValue, oldValue) {
        this.queryRelationModel()
      },
      deep: true
    },
    title: {
      handler (newValue, oldValue) {
        console.log('title', oldValue, '->', newValue)
      }
    },
    masterCurrentRow: {
      handler (newValue, oldValue) {
        if (newValue != null) {
          this.bindDialogDefaultCondition({
            property: this.relationModel.masterIdFieldName,
            relation: 0,
            value: newValue[this.relationModel.masterIdOriginalFieldName]
          })
        }
      },
      deep: true
    },
    bindCurrentRow: {
      handler (newValue, oldValue) {
        this.unbindButton.disabled = (newValue === null) || !this.bindEditAble
        this.positionButton.disabled = (newValue === null) || !this.bindEditAble
      },
      deep: true
    },
    bindSelectedRow: {
      handler (newValue, oldValue) {
        this.unbindButton.disabled = (newValue === null || newValue.length === 0) || !this.bindEditAble
        this.positionButton.disabled = (newValue === null || newValue.length !== 1) || !this.bindEditAble
      },
      deep: true
    },
    unbindCurrentRow: {
      handler (newValue, oldValue) {
        console.log('unbindCurrentRow', newValue)
        this.bindButton.disabled = (newValue === null) || !this.bindEditAble
      },
      deep: true
    },
    unbindSelectedRow: {
      handler (newValue, oldValue) {
        console.log('unbindSelectedRow', newValue)
        this.bindButton.disabled = (newValue === null || newValue.length === 0) || !this.bindEditAble
      },
      deep: true
    },
    bindDialog: {
      handler (newValue, oldValue) {
        if (!newValue.visible) {
          this.bindBasePath = ''
        }
      },
      deep: true
    },
    unbindDialog: {
      handler (newValue, oldValue) {
        console.log(newValue)
      },
      deep: true
    }
  },
  data () {
    return {
      bindDialog: {
        visible: false,
        defaultCondition: []
      },
      bindBasePath: '',
      relationModel: {
        masterIdFieldName: '',
        masterIdOriginalFieldName: '',
        slaveIdFieldName: '',
        slaveIdOriginalFieldName: '',
        orderFieldName: ''
      },
      masterIdQueryParam: {},
      // 已绑定界面
      bindEditAble: false,
      addButton: {
        show: true,
        disabled: false,
        type: 'primary',
        name: '新增',
        icon: 'plus'
      },
      bindQueryData: [],
      bindCurrentRow: null,
      bindSelectedRow: [],
      // 未绑定界面
      unbindButton: {
        show: true,
        disabled: true,
        type: 'warning',
        name: '删除',
        icon: 'trash'
      },
      unbindDialog: {
        visible: false,
        defaultCondition: []
      },
      bindButton: {
        show: true,
        disabled: true,
        type: 'primary',
        name: '绑定',
        icon: 'plus'
      },
      unbindCurrentRow: null,
      unbindSelectedRow: [],
      // 位置变更
      positionButton: {
        show: true,
        disabled: true,
        type: 'primary',
        name: '顺序变更',
        icon: 'align-justify'
      }
    }
  },
  mounted () {
    if (this.basePath !== '') {
      this.queryRelationModel()
    }
  },
  methods: {
    // 获取关系基础配置
    queryRelationModel () {
      const _this = this
      return new Promise((resolve, reject) => _this.fetch(_this.manageApiType(_this.basePath, 'RELATION_MODEL'), null, null, respData => {
        _this.relationModel = {
          ...respData.data
        }
        if (_this.isEmpty(_this.relationModel.orderFieldName)) {
          this.positionButton.show = false
        }
        resolve()
      }, null)
      )
    },
    // 打开已绑定对话框
    setBindDialogVisible (status, blockBindEdit) {
      this.bindDialog.visible = status
      this.bindBasePath = this.basePath
      if (blockBindEdit) {
        this.addButton.disabled = true
        this.bindEditAble = false
      } else {
        this.addButton.disabled = false
        this.bindEditAble = true
      }
    },
    // 已绑定列表处理
    handleBindTableCurrentChange (current, old) {
      this.bindCurrentRow = current
    },
    handleBindTableSelectionChange (selectedData) {
      this.bindSelectedRow = selectedData || []
    },
    // 已绑定列表数据
    handleBindTableQueryData (data) {

    },
    // 添加绑定查询默认条件
    bindDialogDefaultCondition (condition) {
      this.bindDialog.defaultCondition = [condition]
    },
    // 解除绑定
    handleUnbindButton () {
      const body = []
      for (let index in this.bindSelectedRow) {
        const item = {}
        this.$set(item, this.relationModel.masterIdFieldName, this.masterCurrentRow[this.relationModel.masterIdOriginalFieldName])
        this.$set(item, this.relationModel.slaveIdFieldName, this.bindSelectedRow[index][this.relationModel.slaveIdOriginalFieldName])
        body.push(item)
      }
      this.fetch(this.manageApiType(this.basePath, 'UNBIND'), null, body, respData => {
        this.$refs.bindTable.queryData()
      })
    },
    handleAddButton () {
      this.setUnbindDialogVisible(true)
    },
    // 打开未绑定对话框
    setUnbindDialogVisible (status) {
      this.unbindDialog.visible = status
    },
    // 使用定制的查询未绑定从数据方法
    queryUnbind (param, body, callback) {
      const _this = this
      param = {
        ...param,
        masterId: this.masterCurrentRow[this.relationModel.masterIdOriginalFieldName]
      }
      return new Promise((resolve, reject) => _this.fetch(_this.manageApiType(_this.basePath, 'QUERY_UNBIND'), param,
        body, respData => {
          if (callback) {
            callback(respData)
          }
          this.handleUnbindTableCurrentChange(null, this.unbindCurrentRow)
          this.handleUnbindTableSelectionChange()
          resolve()
        }, null)
      )
    },
    // 绑定
    handleBindButton () {
      const body = []
      for (let index in this.unbindSelectedRow) {
        const item = {}
        this.$set(item, this.relationModel.masterIdFieldName, this.masterCurrentRow[this.relationModel.masterIdOriginalFieldName])
        this.$set(item, this.relationModel.slaveIdFieldName, this.unbindSelectedRow[index][this.relationModel.slaveIdOriginalFieldName])
        body.push(item)
      }
      this.fetch(this.manageApiType(this.basePath, 'BIND'), null, body, respData => {
        this.$refs.unbindTable.queryData()
      })
    },
    handleUnbindTableCurrentChange (current, old) {
      this.unbindCurrentRow = current
    },
    handleUnbindTableSelectionChange (selectedData) {
      this.unbindSelectedRow = selectedData || []
    },
    handleUnbindTableQueryData (data) {

    },
    // 位置变更
    handlePositionButton () {
      const body = {}
      this.$set(body, this.relationModel.masterIdFieldName, this.masterCurrentRow[this.relationModel.masterIdOriginalFieldName])
      this.$set(body, this.relationModel.slaveIdFieldName, this.bindSelectedRow[0][this.relationModel.slaveIdOriginalFieldName])
      this.$prompt('请输入位置', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'number',
        inputPlaceholder: '当前位置:' + this.bindSelectedRow[0][this.relationModel.orderFieldName]
      }).then(({value}) => {
        this.fetch(this.manageApiType(this.basePath, 'CHANGE_BIND_ORDER'), {order: value}, body, respData => {
          this.$refs.bindTable.queryData()
        })
      }).catch(() => {

      })
    }

  }
}
</script>

<style scoped>

</style>
